from django.shortcuts import render
import re
import random
import string
import redis
from captcha.image import ImageCaptcha
from django.http import HttpResponse
from django.contrib.auth.hashers import  make_password,check_password
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Users,Massage
# Create your views here.
class checkUsername(APIView):
    def get(self,request,username):
        # 判断用户名是否为空
        if not username:
            return Response({'code':400,'msg':'用户名为空'},status=400)
        # 判断格式是否正确
        if not re.findall(r"^[a-zA-Z][a-zA-Z0-9_]\w{4,15}$",username):
            return Response({'code':400,'msg':'用户名的格式不正确'},status=400)
        # 判断用户名是否存在
        if Users.objects.filter(username=username).count()>0:
            return Response({'code':400,'msg':'用户名已存在'},status=400)
        return Response({'code':200,'msg':'用户名校验通过'})

class checkPassword(APIView):
    def get(self,request,password):
        if not password:
            return Response({'code': 400, 'msg': '密码为空'}, status=400)
        if not re.findall(r"[A-Za-z][A-Za-z0-9_]{4,15}",password):
            return Response({'code': 400, 'msg': '密码格式不正确'}, status=400)
        return Response({'code':200,'msg':'密码校验通过'})


class checkMobile(APIView):
    def get(self,request,mobile):
        # 判断手机号是否为空
        if not mobile:
            return Response({'code':400,'msg':'手机号为空'})
        # 判断格式是否正确
        if not re.findall(r"1[3-9][0-9]{9}$",mobile):
            return Response({'code':400,'msg':'手机号格式不正确'},status=400)
        if Users.objects.filter(mobile=mobile).count()>0:
            return Response({'code':400,'msg':'手机号已存在'})
        return Response({'code':200,'msg':'手机号校验通过'})

class checkImage(APIView):
    def get(self,requst,uuid):
        str_num=''.join(random.sample(string.ascii_letters+string.digits,4))
        r=redis.Redis(host='localhost',port=6379,db=5)
        r.set(uuid,str_num,ex=300)
        r.close()
        cap=ImageCaptcha()
        img=cap.generate(str_num)
        return HttpResponse(content_type="image/png",content=img)
    def post(self,request,uuid):
        code=request.data.get('code')
        r = redis.Redis(host='localhost', port=6379, db=5)
        code2=r.get(uuid)
        r.close()
        if code2:
            a=code2.decode()
        else:
            return Response({'code':400,'msg':'验证码已过期'})
        if a.lower()!=code.lower():
            return Response({'code':400,'msg':'验证码输入错误'})
        return Response({'code': 200, 'msg': '验证码校验通过'})

class Register(APIView):
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        password2=request.data.get('password2')
        mobile=request.data.get('mobile')
        agree=request.data.get('agree')
        if not username:
            return Response({'code':400,'msg':'用户名不能为空'})
        if password!=password2:
            return Response({'code': 400, 'msg': '两次输入的密码不正确'})
        if not mobile:
            return Response({'code': 400, 'msg': '手机号不能为空'})
        if not agree:
            return Response({'code': 400, 'msg': '同意用户协议未勾选'})
        # 写入数据库密文存储密码
        hash_pwd=make_password(password)
        Users.objects.create(
            username=username,password=hash_pwd,mobile=mobile
        )
        return Response({"code":200,'msg':'注册成功'})
from django.db.models import Q
import jwt
from wlgday4 .settings import SECRET_KEY
def get_jwt(user):
    payload={
        'id':user.id,
        'username':user.username,
        'mobile':user.mobile,
    }
    token=jwt.encode(payload=payload,key=SECRET_KEY,algorithm='HS256')
    return token

# 登录
class Login(APIView):
    def post(self,request):
        username=request.data.get('username')
        password=request.data.get('password')
        mobile=request.data.get('mobile')
        try:
            # 可能是用户名 也可能是手机号  获取不到数据出现异常
            user = Users.objects.get(Q(username=username) | Q(mobile=mobile))
        except Exception as e:
            print(e)
            return Response({'code': 400, 'msg': '用户不存在'})
        if not mobile:
            return Response({'code': 400, 'msg': '手机号不存在'})

        if not check_password(password,user.password):
            return Response({'code':400,'msg':'密码不正确'})
        token=get_jwt(user)
        return Response({
            'code':200,
            'msg':'登录成功',
            'token':token,
            'user':{
                'id':user.id,
                'username':user.username,
                'mobile':user.mobile,
            }
        })
class MassageViews(APIView):
    def get(self,request):
        m_data=Massage.objects.all()
        m_list=[]
        for i in m_data:
            m_list.append({
                'id':i.id,
                'name':i.name,
                'sex':i.sex,
                'selfhood':i.selfhood,
                'address':i.address,
            })
        return Response(m_list)
class Update(APIView):
    def put(self,request,id):
        name=request.data.get('name')
        sex=request.data.get('sex')
        selfhood=request.data.get('selfhood')
        address=request.data.get('address')
        Massage.objects.filter(id=id).update(
            name=name,sex=sex,selfhood=selfhood,address=address
        )
        return Response({'code':200,'msg':'修改数据成功'})










